<template>
  <!-- 搜索 -->
  <div class="my-wbox">
    <!-- 搜索 -->
    <div class="my-extra-search">
      <div class="my-slot">
        <div class="my-slot__label">出发地:</div>
        <div class="my-slot__label">省:</div>
        <el-select v-model="search.provinceId" placeholder="请选择乡镇" clearable :disabled="loading"
          @change="onChange('provinceId')" class="my-slot__text" size="large">
          <el-option :label="v.areaName" :value="v.id" v-for="v in provinceIdArr" :index="v.id" />
        </el-select>
        <div class="my-slot__label" v-if="search.superCityFlag != 1">市:</div>
        <el-select v-model="search.cityId" placeholder="请选择村" :disabled="loading" clearable @change="onChange('cityId')"
          class="my-slot__text" v-if="search.superCityFlag != 1" size="large">
          <el-option :label="v.areaName" :value="v.id" v-for="v in cityIdArr" :index="v.id" />
        </el-select>
        <div class="my-slot__label">区:</div>
        <el-select v-model="search.regionId" placeholder="请选择村" :disabled="loading" clearable class="my-slot__text"
          size="large">
          <el-option :label="v.areaName" :value="v.id" v-for="v in regionIdArr" :index="v.id" />
        </el-select>
      </div>
      <div class="my-slot">
        <div class="my-slot__label">目的地:</div>
        <div class="my-slot__label">乡镇:</div>
        <el-select v-model="search.townId" placeholder="请选择乡镇" clearable
          :disabled="loading || (userInfo.roleId == '4' || userInfo.roleId == '5')" @change="onChange('townId')"
          class="my-slot__text" size="large">
          <el-option :label="v.label" :value="v.value" v-for="v in townIdArr" :index="v.value" />
        </el-select>
        <div class="my-slot__label">村:</div>
        <el-select v-model="search.countryId" placeholder="请选择村" :disabled="loading || userInfo.roleId == '5'" clearable
          class="my-slot__text" size="large">
          <el-option :label="v.label" :value="v.value" v-for="v in countryIdArr" :index="v.value" />
        </el-select>
        <div class="my-slot__label">组:</div>
        <el-input v-model="search.groupName" placeholder="请输入" clearable :disabled="loading" class="my-slot__text"
          size="large" />
      </div>

      <div class="my-slot">
        <div class="my-slot__label">最后录入:</div>
        <div class="my-slot__label">开始日期:</div>
        <el-date-picker v-model="search.startDate1" type="date" placeholder="请选择开始日期" class="my-slot__text"
          @change="onChange('time')" :disabled-date="disabledDate1" size="large" />
        <div class="my-slot__label">开始时间:</div>
        <el-time-select v-model="search.startDate2" :min-time='timeLimit.start1' :max-time="timeLimit.end1"
          @change="onChange('time')" start="00:00" step="00:60" end="23:00" placeholder="请选择开始时间" class="my-slot__text"
          size="large" />
        <div class="my-slot__label">结束日期:</div>
        <el-date-picker v-model="search.endDate1" type="date" placeholder="请选择结束日期" class="my-slot__text"
          @change="onChange('time')" :disabled-date="disabledDate2" size="large" />
        <div class="my-slot__label">结束时间:</div>
        <el-time-select v-model="search.endDate2" :min-time='timeLimit.start2' :max-time="timeLimit.end2" start="00:00"
          step="00:60" end="23:00" placeholder="请选择开始时间" class="my-slot__text" @change="onChange('time')"
          size="large" />
      </div>
      <div class="my-slot">
        <div class="my-slot__label"></div>
        <div class="my-slot__label">姓名:</div>
        <el-input v-model="search.name" placeholder="请输入" clearable :disabled="loading" class="my-slot__text"
          size="large" />
        <div class="my-slot__label">手机号:</div>
        <el-input type="number" v-model="search.phone" placeholder="请输入" clearable :disabled="loading"
          class="my-slot__text" size="large" />
        <div class="my-slot__label">抵宁时间:</div>
        <el-date-picker v-model="search.daterange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" class="my-slot__text" size="large">
        </el-date-picker>
      </div>
      <div class="my-slot my-slot__btn">
        <div class="my-slot__flex">
          <div class="my-slot__label"></div>
          <div class="my-slot__label"></div>
          <el-button type="primary" :disabled="loading" @click="onSearch()" size="large">搜索</el-button>
          <el-button :disabled="loading" @click="onSearchClear" size="large">重置</el-button>
        </div>
        <el-button type="primary" :disabled="loading" @click="onExportAll" size="large">全部导出</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <MyTable :tableData="tableData" @listenClick="listenClick">
      <template #default="{ slotData, slotColumn }">
        <div v-if="slotColumn.prop == 'from'">
          {{ slotData.provinceName }}{{ slotData.cityName }}{{ slotData.regionName }}{{ slotData.fromAddress }}</div>
        <div v-if="slotColumn.prop == 'address'">
          {{ slotData.goalTownName }}{{ slotData.goalCountryName }}{{ slotData.goalGroup }}</div>
        <!--  ，0-无，1-绿码；2-黄码；3-红码 -->
        <div v-if="slotColumn.prop == 'healthCode'">
          <span v-if="slotData.healthCode == 0" class="c-color0">无</span>
          <span v-if="slotData.healthCode == 1" class="c-color1">绿码</span>
          <span v-if="slotData.healthCode == 2" class="c-color2">黄码</span>
          <span v-if="slotData.healthCode == 3" class="c-color3">红码</span>
        </div>
      </template>
    </MyTable>
  </div>
</template>
<script setup lang='ts'>
import { ref, reactive, computed } from 'vue'
import { useStore } from '@/store'
import { FunTime } from '@/global/methods'
import MyTable from '@/components/MyTable.vue'
import { ParentTable, SelectObj } from '@/interface/index'
import { getUserInfo, setSearchExtra, getSearchExtra, removeSearchExtra } from '@/global/session'
import { getAreaListApi } from '@/views/account/api/accountApi'
import { getAreaTreeApi } from '@/views/extra/api/extraApi'
import { CityObj, ExtraSearch } from '@/views/extra/interface/interface'
import { useRouter } from 'vue-router'
import http from '@/http/http'
const router = useRouter()
const store = useStore()
let userInfo = reactive({ roleId: '', townId: '', countryId: '', roleAuth: '' })
userInfo = JSON.parse(getUserInfo() as string)
let searchInfo = getSearchExtra()//搜索条件
//监听加载
const loading = computed(() => {
  return store.getters['loading/getLoad']
})
//封装的表格
const tableData = reactive<ParentTable>({//表格的一些数据
  listApi: '/manage/admin/extraPerson/pageList',//列表搜索接口
  listHttp: 'post',//列表接口方法
  search: {},//搜索条件
  column: [//表头
    { prop: 'name', label: '姓名', align: 'left' },
    { prop: 'from', label: '出发地', slot: true },
    { prop: 'address', label: '目的地', slot: true },
    { prop: 'phone', label: '手机号' },
    { prop: 'arriveTime', label: '抵宁时间', tooltip: true },
    { prop: 'healthCode', label: '健康码', slot: true },
    { prop: 'createTime', label: '最后录入时间', tooltip: true }
  ],
  columnBtn: {//操作按钮
    label: '操作',
    align: 'center',
    btn: [
      { name: 'onRouter', text: '详情' },
      { name: 'onExport', text: '导出' },
    ]
  },//表按钮
  index: true,//true 显示序号
  noRender: true
})
// 搜索数据 yaohui
const search = reactive<ExtraSearch>({
  townId: '',
  countryId: '',
  groupName: '',

  provinceId: '',
  cityId: '',
  regionId: '',

  startDate: '',
  endDate: '',
  startDate1: new Date((new Date().getTime() - 24 * 60 * 60 * 1000)),
  endDate1: new Date(),
  startDate2: '16:00',
  endDate2: '16:00',

  arriveStartDate: '',
  arriveEndDate: '',
  daterange: ['', ''],

  name: '',
  phone: '',
  superCityFlag: 0,

  currentPage: 1,
  pageSize: 10

})
//搜索条件改变
const onChange = (val: string) => {
  if (val == 'provinceId') {
    //省
    search.cityId = ''
    search.regionId = ''
    if (search.provinceId) {
      let obj = provinceIdArr.value.find(t => t.id == search.provinceId)
      if (obj?.superCityFlag == 1) {
        //直辖市  展示区
        search.superCityFlag = obj.superCityFlag
        onAreaTreeList({ id: search.provinceId }, 3)
      } else {
        search.superCityFlag = 0
        onAreaTreeList({ id: search.provinceId }, 2)
      }
    }
  } else if (val == 'cityId') {
    //市
    search.regionId = ''
    if (search.cityId) {
      onAreaTreeList({ id: search.cityId }, 3)
    }
  } else if (val == 'time') {
    //录入开始时间 录入结束时间
    timeLimitFun()
  } else if (val == 'townId') {
    //镇  获取乡数据
    onAreaList({ id: search.townId }, 5)
  }
}
//时间限制
const timeLimitFun = () => {
  if (!search.startDate1) {
    search.startDate2 = ''
  }
  if (!search.endDate1) {
    search.endDate2 = ''
  }
  //录入开始时间 日期
  if (search.startDate1?.getDate() == search.endDate1?.getDate()) {
    //开始时间和结束时间是同一天 限制结束时间起始点
    if (search.startDate2 && search.endDate2) {
      //小时都选择了
      let start = new Date(FunTime(search.startDate1) + ' ' + search.startDate2 + ':00').getHours()//开始时间
      let end = new Date(FunTime(search.endDate1) + ' ' + search.endDate2 + ':00').getHours()//结束时间
      if (start > end) {
        //开始时间大于结束时间  则结束时间清零
        search.endDate2 = ''
      }
      timeLimit.end1 = end + 1 > 9 && end + 1 < 24 ? (end + 1) + ':00' : end + 1 > 0 && end + 1 < 10 ? '0' + (end + 1) + ':00' : ''
      timeLimit.start2 = start - 1 > 9 ? (start - 1) + ':00' : start - 1 > 0 && start - 1 < 10 ? '0' + (start - 1) + ':00' : '00:00'
    }
    else if (!search.startDate2 && search.endDate2) {
      //选择了结束时间
      let end = new Date(FunTime(search.endDate1) + ' ' + search.endDate2 + ':00').getHours()//结束时间
      timeLimit.end1 = end + 1 > 9 && end + 1 < 22 ? (end + 1) + ':00' : end + 1 > 0 && end + 1 < 10 ? '0' + (end + 1) + ':00' : ''
      timeLimit.start2 = ''
    } else if (search.startDate2 && !search.endDate2) {
      //选择了开始时间
      let start = new Date(FunTime(search.startDate1) + ' ' + search.startDate2 + ':00').getHours()//开始时间
      timeLimit.end1 = ''
      timeLimit.start2 = start - 1 > 9 ? (start - 1) + ':00' : start - 1 > 0 && start - 1 < 10 ? '0' + (start - 1) + ':00' : '00:00'
    } else {
      //都没选择
      timeLimit.end1 = ''
      timeLimit.start2 = ''
    }
  } else {
    //不是同一天
    timeLimit.end1 = ''
    timeLimit.start2 = ''
  }
}
// 录入开始时间禁用
const disabledDate1 = (time: Date) => {
  if (search.endDate1) {
    return time.getTime() > search.endDate1.getTime() || time.getTime() > Date.now()
  } else {
    return time.getTime() > Date.now()
  }
}
// 录入结束时间禁用
const disabledDate2 = (time: Date) => {
  if (search.startDate1) {
    return time.getTime() < search.startDate1.getTime() || time.getTime() > Date.now() + 24 * 60 * 60 * 1000
  } else {
    time.getTime() > Date.now() + 24 * 60 * 60 * 1000
  }
}
const timeLimit = reactive({
  start1: '',
  end1: '',
  start2: '',
  end2: '',
})
//搜索
const onSearch = (str?:string) => {
  //处理录入时间 开始时间 结束时间
  let startDateT = search.startDate2 ? search.startDate2 : '00:00'
  let endDateT = search.endDate2 ? search.endDate2 : '00:00'
  search.startDate = search.startDate1 ? FunTime(search.startDate1) + ' ' + startDateT + ':00' : ''
  search.endDate = search.endDate1 ? FunTime(search.endDate1) + ' ' + endDateT + ':00' : ''
  // 处理抵宁 开始时间 结束时间
  if (search.daterange.length > 0) {
    search.arriveStartDate = search.daterange[0] ? FunTime(search.daterange[0]) : ''
    search.arriveEndDate = search.daterange[1] ? FunTime(search.daterange[1]) : ''
  } else {
    search.arriveStartDate = ''
    search.arriveEndDate = ''
  }
  if(!str){
    search.currentPage=1
    search.pageSize=10
  }
  let { daterange, startDate1, startDate2, endDate1, endDate2, superCityFlag, currentPage, pageSize, ...obj } = search
  tableData.search = obj
  tableData.noRender = false//显示表格
  //刷新表格
  store.commit('refresh/setRefresh', !store.getters['refresh/getRefresh'])
  removeSearchExtra()//清除搜索条件
  //把搜索条件记录一下
  setSearchExtra(JSON.stringify(search))
}
//列表搜索重置 清空插槽里面的内容
const onSearchClear = (val: any) => {
  if (userInfo.roleId == '1' || userInfo.roleId == '2' || userInfo.roleId == '3') {
    // // "roleId": //角色id 1、超级管理员  2、市级管理员 3、市级督察员
    search.townId = ''
    search.countryId = ''
  } else if (userInfo.roleId == '4') {
    // "roleId": //角色id  4、镇级管理员  5、村级管理员
    search.countryId = ''
    search.townId = userInfo.townId
  } else if (userInfo.roleId == '5') {
    //"roleId": //角色id   5、村级管理员
    val.townId = userInfo.townId
    val.countryId = userInfo.countryId
  }
  search.groupName = ''
  search.provinceId = ''
  search.cityId = ''
  search.regionId = ''

  search.startDate = ''
  search.endDate = ''
  search.startDate1 = new Date((new Date().getTime() - 24 * 60 * 60 * 1000))
  search.endDate1 = new Date()
  search.startDate2 = '16:00'
  search.endDate2 = '16:00'

  search.arriveStartDate = ''
  search.arriveEndDate = ''
  search.daterange = ['', '']

  search.name = ''
  search.phone = ''
  search.superCityFlag = 0
  onSearch()
}
//详情
const onRouter = (row: any) => {
  setSearchExtra(JSON.stringify(search))
  router.push({ name: 'extraDetail', query: { name: row.name, phone: row.phone } })
}
//全部导出
const onExportAll = () => {
  let params = tableData.search
  FunApi('/manage/admin/extraPerson/exportAll', params)
}
//单个导出
const onExport = (val: any) => {
  let params = {
    name: val.name,
    phone: val.phone
  }
  FunApi('/manage/admin/extraPerson/exportOne', params)
}
const FunApi = async (url: string, params: any) => {
  try {
    let res = await http.post(url, params)
    if (res?.code === 0 && res.data) {
      window.open(res.data)
    }
  } catch {
  }
}
//分页 一页多少条数 yaohui
const onListenPageSize = (val: number) => {
  search.pageSize = val
}
//分页  当前页码
const onListenPageIndex = (val: number) => {
  search.currentPage = val
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = { 'onRouter': onRouter, 'onExport': onExport, 'onListenPageSize': onListenPageSize, 'onListenPageIndex': onListenPageIndex }
// 监听子级表格  传过来的方法禁用
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
//获取所有乡镇
let townIdArr = ref<SelectObj[]>([])//乡镇
let countryIdArr = ref<SelectObj[]>([])//存
const onAreaList = async (params: any, num: number) => {
  try {
    let res = await getAreaListApi(params)
    if (res?.code == 0) {
      let arr: SelectObj[] = []
      res.data.forEach(t => {
        if (userInfo.roleId == '3' && num == 4) {
          //督察员
          let roleAuth = userInfo.roleAuth.split(',')
          roleAuth.forEach(v => {
            if (t.areaCode == v) {
              arr.push({ label: t.name, value: t.areaCode })
            }
          })
        } else {
          arr.push({ label: t.name, value: t.areaCode })
        }
      })
      if (num == 4) {
        townIdArr.value = arr
      } else {
        countryIdArr.value = arr
      }
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//获取省市区getAreaListApi
// provinceId: '',
//   cityId: '',
//   regionId: ''
let provinceIdArr = ref<CityObj[]>([])//省
let cityIdArr = ref<CityObj[]>([])//市
let regionIdArr = ref<CityObj[]>([])//区
const onAreaTreeList = async (params: any, num: number) => {
  try {
    let res = await getAreaTreeApi(params)
    if (res?.code == 0) {
      if (num == 1) {
        //省
        provinceIdArr.value = res.data
      } else if (num == 2) {
        //市
        cityIdArr.value = res.data
      } else {
        //区
        regionIdArr.value = res.data
      }
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}

//详情页返回的搜索条件保留
if (searchInfo) {
  let searchObj = JSON.parse(searchInfo)
  searchObj.startDate1 = new Date(searchObj.startDate1)
  searchObj.endDate1 = new Date(searchObj.endDate1)
  Object.keys(search).map(key => {
    search[key] = searchObj[key]
  })
  onAreaTreeList({ id: '0' }, 1)
  if (searchObj.provinceId) {
    //如果有省  查省下面的市
    if (searchObj.superCityFlag == 1) {
      //直辖市  展示区
      onAreaTreeList({ id: search.provinceId }, 3)
    } else {
      onAreaTreeList({ id: search.provinceId }, 2)
    }
  }
  // debugger
  if (searchObj.cityId) {
    //如果有市且不是直辖市 查市下面的区
    onAreaTreeList({ id: search.cityId }, 3)
  }
  onAreaList({ id: '0' }, 4)
  if (searchObj.townId) {
    //如果有镇  查镇下面的乡
    onAreaList({ id: search.townId }, 5)
  }
  onSearch('sessions')
} else {
  onAreaTreeList({ id: '0' }, 1)
  if (userInfo.roleId == '1' || userInfo.roleId == '2' || userInfo.roleId == '3') {
    onAreaList({ id: '0' }, 4)
  } else if (userInfo.roleId == '4') {
    search.townId = userInfo.townId
    onAreaList({ id: '0' }, 4)
    onAreaList({ id: userInfo.townId }, 5)

  } else if (userInfo.roleId == '5') {
    search.townId = userInfo.townId
    search.countryId = userInfo.countryId
    onAreaList({ id: '0' }, 4)
    onAreaList({ id: userInfo.townId }, 5)
  }
  onSearch()
}
</script>
<style scoped lang='scss'>
.my-slot {
  width: 100%;
  display: flex;
  align-items: center;
  line-height: 40px;

  &__text,
  :deep(.el-date-editor) {
    margin: 0 20px 10px 0;
    width: 200px;
    height: 40px;
  }

  :deep(.el-date-editor--daterange) {
    padding: 0 11px;
    width: 300px;
    flex-grow: inherit;
  }

  &__flex {
    flex: 1;
    display: flex;
    align-items: center;
  }

  &__label {
    font-size: 14px;
    white-space: nowrap;
    margin: 0 8px 10px 0;
    min-width: 80px;
    text-align: right;
  }

  &__btn {
    margin-bottom: 20px;
  }
}
</style>